import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token'))
  const notifications = ref([])
  const unreadCount = ref(0)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const avatar = computed(() => userInfo.value?.avatar || 'https://via.placeholder.com/32')
  const username = computed(() => userInfo.value?.username || 'Guest')

  // 登录
  const login = async (credentials) => {
    try {
      // TODO: 实现登录 API 调用
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials)
      })
      const data = await response.json()
      
      if (data.token) {
        token.value = data.token
        localStorage.setItem('token', data.token)
        await fetchUserInfo()
        return true
      }
      return false
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('token')
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      // TODO: 实现获取用户信息 API 调用
      const response = await fetch('/api/user/info', {
        headers: { 
          'Authorization': `Bearer ${token.value}`
        }
      })
      const data = await response.json()
      userInfo.value = data
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 获取通知
  const fetchNotifications = async () => {
    try {
      // TODO: 实现获取通知 API 调用
      const response = await fetch('/api/notifications', {
        headers: { 
          'Authorization': `Bearer ${token.value}`
        }
      })
      const data = await response.json()
      notifications.value = data.notifications
      unreadCount.value = data.unreadCount
    } catch (error) {
      console.error('获取通知失败:', error)
    }
  }

  // 标记通知为已读
  const markNotificationRead = async (id) => {
    try {
      await fetch(`/api/notifications/${id}/read`, {
        method: 'POST',
        headers: { 
          'Authorization': `Bearer ${token.value}`
        }
      })
      await fetchNotifications()
    } catch (error) {
      console.error('标记通知失败:', error)
    }
  }

  // 初始化
  if (token.value) {
    fetchUserInfo()
    fetchNotifications()
  }

  return {
    userInfo,
    token,
    notifications,
    unreadCount,
    isLoggedIn,
    avatar,
    username,
    login,
    logout,
    fetchUserInfo,
    fetchNotifications,
    markNotificationRead
  }
}) 